/**
 * @Author DingBaoyong
 * @Date 2020-08-18 14:49
 * @Desc 封装方法公共js库
 */
//全局常量
const ALARMTYPEID = ["请选择", "红色报警", "橙色报警", "黄色报警"];
//存放省、市、县数据或者省、市、县、隐患点数据)
var levelData = null;

class Param{
	constructor(id, keyName, keyValue, pKeyName, pKeyValue, value = null, prepend = false) {
		this.id = id;
		this.keyName = keyName;
		this.keyValue = keyValue;
		this.pKeyName = pKeyName;
		this.pKeyValue = pKeyValue;
		this.value = value;
		this.prepend = prepend;
	}
}

$.ajaxSetup({
	error : function (XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==420){
			alert('会话失效！将返回登录页面。');
			location.reload() ;
		}
		if(XMLHttpRequest.status==520){
			alert('系统繁忙，请稍后重试！');
		}
	}
});

function generateMixed(n) {
     var res = "";
     for(var i = 0; i < n ; i ++) {      
         var id = Math.floor(Math.random()*16);
         res += color_chars[id];
     }
     return res;
}

/**
 * 管理列表页面通用js 
 */

/**
 * 表单验证提交
 * @param editForm 要提交的表单id
 * @param beforeSubmit 提交前的formdata处理
 * @param mySaveModal 弹出层的id
 * @param datagrid 提交后要刷新的easyui列表id
 */
 function editValidataSubmit(editForm, beforeSubmit, mySaveModal, datagrid) {
	let handleActionFormBeforeSubmit;
 	if(beforeSubmit == null){
		handleActionFormBeforeSubmit = () => true;
	}else{
		handleActionFormBeforeSubmit = beforeSubmit;
	}
	let ajax_option = {
		beforeSubmit: handleActionFormBeforeSubmit,
		dataType: "json",
		success : function(data) {
			if (data.flag == 1) {
				if(editForm == "supervisionForm"){
					alert("保存成功，请重新登录!");
				}else{
					alert("保存成功!");
				}
				$("#"+mySaveModal).modal('hide');
				refreshDataGrid(datagrid);
			} else {
				alert("操作失败，原因：" + data.msg);
			}
		}
	};

	$("#"+editForm).on("submit", function(e) {
		e.preventDefault();
		if($("#"+editForm).valid()){
			$('#'+editForm).ajaxSubmit(ajax_option);
			return false;
		}
	});
	$("#"+editForm).validate();
}

/*
 * 图片上传公用方法 上传多张图片 传参form,展示图片的对象imgObj,隐藏图片路径的对象urlObj
 * */
 var fileString = "";//记录图片地址
 function uploadFile(form,imgObj,urlObj,text){
	fileString = $("#"+urlObj).val();
    $('#'+form).ajaxSubmit({
		success : function(data) {
			if (data.flag == 1) {
				alert("上传成功");
				var _base64=data.base64,
					_imgUrl=data.url;

				$("#"+imgObj).attr("src",severHttpUrl+_imgUrl);
				if(fileString!=""){//显示多张
					//fileString+=",";
					if(fileString.split(",").length==1){
						fileString+=",";
					}
					var _imgHtml = "<div class='js-avatar text-center js-avatar-pos'>" +
							"<a href='javascript:;' class='view-img'>" +
							"<img src='"+severHttpUrl+_imgUrl+"' alt=''>" +
							"<strong>"+text+"</strong>" +
							"</a><a href='javascript:;' class='delete-img' id='delete-add-img_'>删除</a>" +
							"</div>";
					$("#"+imgObj).parents(".js-avatar").append(_imgHtml);
					fileString +=_imgUrl+",";//拼接多长图片,编辑的时候走此方法
				}else{
					fileString=_imgUrl+",";//添加的时候
					$(".delete-img").show();
				}
				$("#"+urlObj).val(fileString);//把值赋在隐藏域内

			} else {
				alert("操作失败，原因：" + data.msg);
			}
		}
    });
	return false;
 }

 /*
  * 图片上传，单张图片上传
  * */
 function uploadFileOrg(form,imgObj,urlObj){
	 $("#"+form).on('submit', function(e) {
        e.preventDefault(); 
        $('#'+form).ajaxSubmit({
    		success : function(data) {
    			if (data.flag == 1) {
    				alert("上传成功");
    				var _base64=data.base64,
    					_imgUrl=data.url;

    				$("#"+imgObj).attr("src",severHttpUrl+_imgUrl);
    				$("#"+urlObj).val(_imgUrl);
    			} else {
    				alert("操作失败，原因：" + data.msg);
    			}
    		}
     	});
    	return false; 
	 });
 }
 
 function uploadFileSignal(form,imgObj,urlObj){
	 $('#'+form).ajaxSubmit({
		success : function(data) {
			if (data.flag == 1) {
				alert("上传成功");
				var _base64=data.base64,
					_imgUrl=data.url;

				$("#"+imgObj).attr("src",severHttpUrl+_imgUrl);
				$("#"+urlObj).val(_imgUrl);
			} else {
				alert("操作失败，原因：" + data.msg);
			}
		}
 	});
	return false;
 }
 
/**
 * 编辑弹出窗体赋值
 * @param editForm 弹出窗体的提交表单id
 * @param mySaveModal 弹出层的id
 * @param url 读取数据的url路径
 * @param editId 要编辑的记录id
 */
function editShow(editForm,mySaveModal,url,editId){
	$("#"+mySaveModal).modal('show');		
	clearEditForm(editForm);
	$.post(url, { id: editId }, function (data) {
		$("#"+editForm+" input[type=hidden]").each(function(){
  		  $(this).val(data[$(this).attr("name")]);
		});
		
    	  $("#"+editForm+" input[type=text]").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
    		});
    	  
    	  $("#"+editForm+" textarea").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
    		});
    	  
    	  $("#"+editForm+" input:radio").each(function(){
    		  if($(this).val()==data[$(this).attr("name")]){
    			  $(this).prop('checked',true);
    		  }        		 
    		});
    	  $("#"+editForm+" input:checkbox").each(function(){
    		  var values=data[$(this).attr("name")];
    		  var arr=values.split(",");
    		  var i;
    		  for(i=0;i<arr.length;i++){
    			  if($(this).val()==arr[i]){
    			  $(this).prop('checked',true);}
    		  }      		 
    	  });
    	  
    	  $("#"+editForm+" select").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
		  });
    });
}

/**
 * 编辑弹出窗体赋值
 * @param editForm 弹出窗体的提交表单
 * @param mySaveModal 弹出层的id
 * @param url 读取数据的url路径
 * @prram filedName 字段名称
 * @param editValue 要编辑的记录的字段值
 */
function fieldNameEditShow(editForm,mySaveModal,url,fieldName,editValue) {
	$("#"+mySaveModal).modal('show');		
	clearEditForm(editForm);
	$.post(url+"?"+fieldName+"="+editValue, function (data) {
		$("#"+editForm+" input[type=hidden]").each(function(){
  		  $(this).val(data[$(this).attr("name")]);
  			});
		
    	  $("#"+editForm+" input[type=text]").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
    		});
    	  
    	  $("#"+editForm+" textarea").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
    		});
    	  
    	  $("#"+editForm+" input:radio").each(function(){
    		  if($(this).val()==data[$(this).attr("name")]){
    			  $(this).prop('checked',true);
    		  }        		 
    		});
    	  
    	  $("#"+editForm+" select").each(function(){
    		  $(this).val(data[$(this).attr("name")]);
    		});
    	  
    });
}


/**
 * 删除 方法
 * @param url 执行删除的url
 * @param id 要删除的记录id
 * @param datagrid 删除操作后要刷新的easyui列表id
 */
function deleteDo(url, id, datagrid, showText){
	let _showText = showText;
	if(showText == "" || showText == "undefined" || showText == null){
		_showText = "删除";
	}
	swal({
	    title: "你确定吗?",
	    text: _showText + "后将不能恢复!",
	    type: "warning",
	    showCancelButton: true,
	    confirmButtonColor: "#4fa7f3",
	    cancelButtonColor: "#d57171",
	    confirmButtonText: "是的,"+ _showText +"!",
		cancelButtonText: "不, 取消!",
		allowOutsideClick: false
	}).then(function () {
		$.post(
			url,
			{id: id},
			function (data) {
				if(data.flag == 1) {
					swal(
						_showText + "成功!",
						"",
						"success"
					)
					//刷新表单
					refreshDataGrid(datagrid);
				}else{
					swal(
						_showText + "失败!",
						data.msg,
						"error"
					)
				}
			},
			"json"
		);
	}, function (cancel) {
		if(cancel === "cancel"){
			// ignore 取消操作不做处理
		}
	})
}

/**
 * 批量删除方法
 * @param event 批量删除时传入的参数
 * 格式 {url：执行删除的url路径,datagrid:删除后要刷新的easyui列表id}
 * 如：{url:"../school/dellist.shtml",datagrid:"datagrid"}
 */
function deleteBatchDo(event){	
	//获取选择的ID
	var rows = $("#"+event.data.datagrid).datagrid('getSelections');
/*	var columnCount = $("#"+event.data.datagrid).GetColumns().GetCount();
	alert(columnCount);*/
	var _showText=event.data.showText;
	if(_showText==""||_showText==null||_showText=='undefined'){
		_showText="删除";
	}
    if (rows.length >= 1) { 
        //遍历出选择的数据
        var checkIds = new Array();
        for (var i = 0; i < rows.length; i++) {
        	/*alert(i);
        	var rowLength = rows[i].length-1;
        	alert(rowLength);*/
        	checkIds.push(rows[i].id);
        }
        //确认删除信息
        if(confirm("您确认要"+_showText+"选中的这些信息吗？")){
                //异步实现删除
                $.post(event.data.url, { ids: checkIds.join(',') }, function (data) {
                	 if (data.flag == "1") {
                		 alert(""+_showText+"成功");
                        //刷新表单，清空选择的数据
                		 refreshDataGrid(event.data.datagrid);
                    }
                    else {
                    	alert(""+_showText+"失败，原因：" + data.msg);
                        refreshDataGrid(event.data.datagrid);
                    }
                });
            }
    }
    else {
    	alert("请选择您要"+_showText+"的信息!");
    }
} 


/**
 * 清空编辑窗体
 * @param editForm 编辑提交窗体id
 * @param btnreset 重置按钮id
 */
function clearEditForm(editForm){
	$("#" + editForm+ " select").empty();
	$("#"+editForm+" input[type=hidden]").each(function(){
		$(this).val("");
	});
	$(".error").text("");
	$("img").attr("src", "");
	$("#"+editForm+"")[0].reset();
}

/**
 * 刷新easyui列表
 * @param datagrid 要刷新easyui列表的id 
 */
function refreshDataGrid(datagrid){
	if(datagrid != null){
		if($("#"+datagrid).attr("class").indexOf("easyui-datagrid") == 0) {
			$("#"+datagrid).datagrid("reload");
			$("#"+datagrid).datagrid("clearSelections");
		}else if($("#"+datagrid).attr("name").indexOf("easyui-datagrid") == 0){
			$("#"+datagrid).datagrid("reload");
			$("#"+datagrid).datagrid("clearSelections");
		}else{
			$("#"+datagrid).treegrid("reload");
		}
	}
}

//日期"yyyy-MM-dd" 获取当天 GetDateStr(0); //获取前天GetDateStr(-1);//后天 GetDateStr(1);
function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    if(m<10)
    	m="0"+m;
    if(d<10)
    	d="0"+d;
    return y+"-"+m+"-"+d;
}


/**  
 * 时间对象的格式化   format="yyyy-MM-dd hh:mm:ss";  
 */  
 Date.prototype.format = function(format){
    let o = {
	    "M+" : this.getMonth() + 1,  
	    "d+" : this.getDate(),  
	    "h+" : this.getHours(),  
	    "m+" : this.getMinutes(),  
	    "s+" : this.getSeconds(),  
	    "q+" : Math.floor((this.getMonth() + 3) / 3),  
	    "S" : this.getMilliseconds()  
    }    
    if (/(y+)/.test(format)){  
    	format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
    }    
    for (var k in o){  
	    if (new RegExp("(" + k + ")").test(format)){  
		    format = format.replace(RegExp.$1, RegExp.$1.length == 1? o[k]: ("00" + o[k]).substr(("" + o[k]).length));  
	    }  
    }  
    return format;  
 }

 function formatDateTimeStr(dateTimeStr){
	 let regExp = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}).0$/;
	 let tmpDateTime = dateTimeStr.match(regExp);
	 let date = tmpDateTime[1];
	 let time = tmpDateTime[2];
	 return {date, time}
 }


//拖动范围控制
 function onDrag(e){
     var d = e.data;
     if (d.left < 0){d.left = 0}
     if (d.top < 0){d.top = 0}
     if (d.left + $(d.target).width() + $(d.target).outerWidth() > document.documentElement.clientWidth){
         d.left = document.documentElement.clientWidth - $(d.target).outerWidth();
         //拖动时候清除左margin
         $(d.target).css("margin-left",0);
     }
     if (d.top + $(d.target).outerHeight() > document.documentElement.clientHeight){
         d.top = document.documentElement.clientHeight - $(d.target).outerHeight();
     }
 }
 

//初始化日期插件 ,传入开始时间，结束时间
function initStarEndDatepicker(startDate,endDate){
	$("#"+startDate).datepicker({
		dateFormat: "yy-mm-dd",
		onClose: function (selectedDate) {
			if (selectedDate){
				$("#"+endDate).datepicker("option", "minDate", selectedDate);
			}
		}
	});
	$("#"+endDate).datepicker({
		dateFormat: "yy-mm-dd",
		onClose: function (selectedDate) {
			if (selectedDate){
				$("#"+startDate).datepicker("option", "maxDate", selectedDate);
			}
		}
	});	
}

 //初始化单个日期时间
function initDatepicker(obj){
	if(obj!=""||obj!=null){
		var objs=obj.split(",");
		if(objs.length>1){//多个
			for(var i=0;i<objs.length;i++){
				 $("#"+objs[i]).datepicker({
				     minDate: new Date(),
				     SetSelectedDate:new Date(),
				     numberOfMonths: 1,
				     dateFormat: "yy-mm-dd",
				     showClearButton:true //清除
				 });	
			}
		}else{//单个
			 $("#"+obj).datepicker({
			     minDate: new Date(),
			     SetSelectedDate:new Date(),
			     numberOfMonths: 1,
			     dateFormat: "yy-mm-dd",
			     showClearButton:true //清除
			 });	
		}
	}
}

//判断是否启用状态
let showUseFlag = value => {
	let useFlagHtml = "";
	if(value == "1"){
		useFlagHtml = "<i class=\"fi-check \"></i>";
	}else if(value == "0"){
		useFlagHtml = "<i class=\"fi-cross \"></i>";
	}
	return useFlagHtml;
}

//初始化顶级(省级)
function initProvArea(select){
	let info ='<option value="">请选择</option><option value="110000">北京市</option><option value="120000">天津市</option><option value="130000">河北省</option><option value="140000">山西省</option><option value="150000">内蒙古自治区</option><option value="210000">辽宁省</option><option value="220000">吉林省</option><option value="230000">黑龙江省</option><option value="310000">上海市</option><option value="320000">江苏省</option><option value="330000">浙江省</option><option value="340000">安徽省</option><option value="350000">福建省</option><option value="360000">江西省</option><option value="370000">山东省</option><option value="410000">河南省</option><option value="420000">湖北省</option><option value="430000">湖南省</option><option value="440000">广东省</option><option value="450000">广西壮族自治区</option><option value="460000">海南省</option><option value="500000">重庆市</option><option value="510000">四川省</option><option value="520000">贵州省</option><option value="530000">云南省</option><option value="540000">西藏自治区</option><option value="610000">陕西省</option><option value="620000">甘肃省</option><option value="630000">青海省</option><option value="640000">宁夏回族自治区</option><option value="650000">新疆维吾尔自治区</option><option value="710000">台湾省</option><option value="810000">香港特别行政区</option><option value="820000">澳门特别行政区</option>';
	$('#'+select).append(info);
}

//初始化下一级地区
function initNextArea(select, pid, value){
 	new Promise((resolve, reject) => {
		$.ajax({
			url: basePath + "zoneCode/listByPid.html",
			data: "pid=" + pid,
			dataType: "json",
			success: function(data){
				if(data != null){
					resolve(data);
				}
			}
		});
	}).then(function (data) {
		$("#"+ select).empty();
		$("#"+ select).prepend("<option value=''>请选择</option>");
		if(data.length > 0){
			for(let i = 0; i < data.length; i++){
				$("#"+ select).append("<option value='"+data[i].id +"'>"+data[i].name+"</option>");
			}
		}
		if(value != null){
			setselect(select, value);
			$("#select2-"+ select +"-container").text($("#"+ select +" option:selected").text());
		}
	})
}

//根据对象让select选中某一项
function selectItem(objSelect, objItemValue) {
	if(!objSelect){
		return;
	}
    for(let j = 0; j < objSelect.options.length; j++){
		if(objSelect[j].value == objItemValue){
			objSelect[j].selected="selected";
		}
	}
}

//根据id让select选中某一项
function setselect(id, value){
	let group = document.getElementById(id);
	if(!group){
		return;	
	}
	for(let j=0; j < group.length; j++){
		if(group[j].value == value){
			group[j].selected = "selected";
			return true;
		}
	}
	return false;
}

//将select option中的值转化为数组
function selOptValToArr(id) {
	let arr = new Array();
	$("#"+ id +" option").each(function () {
		arr.push($(this).val());
	});
	return arr;
}

//根据index从预定义常量数组中取出对应数据
function getValueByIndex(id, value) {
 	let valArr = [];
	let arr = eval(id.toUpperCase());
	for(let index in value.split(",")){
		valArr.push(arr[index]);
	}
	return valArr.join(",");
}

//根据预定义常量数据初始化单选下拉列表
function initSingleSelect(id, value){
	let str;
	let arr = eval(id.toUpperCase());
	$("#"+id).empty();
	if(value == null){
		for(let index = 0; index < arr.length; index ++){
			if(index == 0){
				str += "<option value selected='selected'>"+ arr[index] +"</option>";
			}else{
				str += "<option value='"+ index +"'>"+ arr[index] +"</option>";
			}
		}
	}else if(value != null){
		let selectedArr = value.split(",");
		for(let index = 0; index < arr.length; index ++){
			let flag = false;
			for(let item in selectedArr){
				if(index == selectedArr[item]){
					flag = true;
				}
			}
			if(flag){
				if(index == 0){
					str += "<option value selected='selected'>"+ arr[index] +"</option>";
				}else{
					str += "<option value='"+ index +"' selected='selected'>"+ arr[index] +"</option>";
				}
			}else{
				if(index == 0){
					str += "<option value>"+ arr[index] +"</option>";
				}else{
					str += "<option value='"+ index +"'>"+ arr[index] +"</option>";
				}
			}
		}
	}
	$("#" + id).append(str);
}

//根据对象数组初始化单选下拉列表
function initObjArrSingleSelect(id, value){
	let str;
	let arr = eval(id.toUpperCase());
	$("#"+id).empty();
	if(value == null){
		for(let index = 0; index < arr.length; index ++){
			if(index == 0){
				str += "<option value selected='selected'>"+ arr[index].name +"</option>";
			}else{
				str += "<option value='"+ arr[index].value +"'>"+ arr[index].name +"</option>";
			}
		}
	}else if(value != null){
		let selectedArr = value.split(",");
		for(let index = 0; index < arr.length; index ++){
			let flag = false;
			for(let item in selectedArr){
				if(arr[index].value == selectedArr[item]){
					flag = true;
				}
			}
			if(flag){
				if(index == 0){
					str += "<option value selected='selected'>"+ arr[index].name +"</option>";
				}else{
					str += "<option value='"+ arr[index].value +"' selected='selected'>"+ arr[index].name +"</option>";
				}
			}else{
				if(index == 0){
					str += "<option value>"+ arr[index].name +"</option>";
				}else{
					str += "<option value='"+ arr[index].value +"'>"+ arr[index].name +"</option>";
				}
			}
		}
	}
	$("#" + id).append(str);
}

//根据预定义常量数据初始化自带key_value的下拉列表
function initKeyValueSelectByCondition(id, condition, value){
	let str = "";
	let arr = [];
	if(condition != null && condition != ""){
		arr = eval((condition + "_" + id).toUpperCase());
	}else{
		arr = eval(id.toUpperCase());
	}	
	$("#"+id).empty();
	if(value == null){
		for(let index = 0; index < arr.length; index ++){
			let mapArr = arr[index].split("_");
			let key = mapArr[0];
			let value = mapArr[1];
			if(index == 0){
				str += "<option value selected='selected'>"+ value +"</option>";
			}else{
				str += "<option value='"+ key +"'>"+ value +"</option>";
			}
		}
	}else if(value != null){
		let selectedArr = value.split(",");
		for(let index = 0; index < arr.length; index ++){
			let mapArr = arr[index].split("_");
			let key = mapArr[0];
			let value = mapArr[1];
			let flag = false;
			for(let item in selectedArr){
				if(key == selectedArr[item]){
					flag = true;
				}
			}
			if(flag){
				if(index == 0){
					str += "<option value selected='selected'>"+ value +"</option>";
				}else{
					str += "<option value='"+ key +"' selected='selected'>"+ value +"</option>";
				}
			}else{
				if(index == 0){
					str += "<option value>"+ value +"</option>";
				}else{
					str += "<option value='"+ key +"'>"+ value +"</option>";
				}
			}
		}
	}
	$("#" + id).append(str);
}

//初始化多选下拉列表
function initMultiSelect(id, value){
	let str = "";
	let arr = eval(id.toUpperCase());
	$("#" + id).empty();
	if(value == null){
		for(let index = 0; index < arr.length; index ++){
			str += "<option value='"+ (index + 1) +"'>"+ arr[index] +"</option>";
		}
	}else if(value != null){
		let selectedArr = value.split(",");
		for(let index = 0; index < arr.length; index ++){
			let flag = false;
			for(let item in selectedArr){
				if(index+1 == selectedArr[item]){
					flag = true;
				}
			}
			if(flag){
				str += "<option value='"+ (index + 1) +"' selected='selected'>"+ arr[index] +"</option>";
			}else{
				str += "<option value='"+ (index + 1) +"'>"+ arr[index] +"</option>";
			}
		}
	}
	$("#" + id).append(str);
}

//id：元素节点id，ajaxOptions: ajax请求参数， keyName:键名，keyValue：键名，value：选中值, prepend:是否预先添加选项
let initSelectByAjax = (id, ajaxOptions, keyName, keyValue, value, prepend) =>{
	$.ajax({
		url: ajaxOptions.url,
		type: "post",
		data: ajaxOptions.data,
		dataType: "json",
		success: function (data) {
			if(data != null){
				initSelectByAjaxData({data, id, keyName, keyValue, value, prepend});
			}
		}
	});
}

//根据ajax返回的数据进行加载下拉列表
let initSelectByAjaxData = ({data, id, keyName, keyValue, value, prepend}) =>{
	let str = "";
	$("#" + id).empty();
	if(prepend){
		$("#"+ id).prepend("<option value=''>请选择</option>");
	}
	if(value == null){
		for(let item of data){
			str += "<option value='"+ item[keyName] +"'>"+ item[keyValue] +"</option>";
		}
	}else if(value != null){
		let selectedArr = value.split(",");
		for(let item of data){
			let flag = false;
			for(let selectedItem of selectedArr){
				if(item[keyName] == selectedItem){
					flag = true;
				}
			}
			if(flag){
				str += "<option value='"+ item[keyName] +"' selected='selected'>"+ item[keyValue] +"</option>";
			}else{
				str += "<option value='"+ item[keyName] +"'>"+ item[keyValue] +"</option>";
			}
		}
	}
	$("#" + id).append(str);
}

//初始化省、市、县区、隐患点下拉框(此处必须用var声明，方便覆盖)
var initLevelSelect = extraData => {
	if(levelData == null){
		getDataByAjax("hiddenPoint/queryAll.html", "get", null, "json", extraData);
	}else{
		dealWithData(levelData, extraData);
	}
}

//封装ajax请求从后台获取数据
function getDataByAjax(url, type, data, dataType, extraData) {
	new Promise((resolve, reject) => {
		$.ajax({
			type: type,
			url: basePath + url,
			data: data,
			dataType: dataType,
			success: function(data){
				if(data != null){
					resolve(data);
				}
			},
			error: function (xhr, textStatus, errorThrown) {
				reject(xhr.responseText);
			}
		});
	}).then(function (value) {
		ajaxCallBack(value, extraData);
	},function (reason) {
		swal(reason).catch(swal.noop);
	})
}


//回调函数
var ajaxCallBack = (data, extraData) =>{
	levelData = data;
	if(extraData != null){
		dealWithData(levelData, extraData);
	}
}

//处理节点数据
let dealWithData = (data, extraData) =>{
	let str = "";
	let dataMap = new Map();
	for(let index in data){
		dataMap.set(data[index][extraData.keyName], data[index]);
	}
	$("#"+ extraData.id).empty();
	if(extraData.prepend){
		$("#"+ extraData.id).prepend("<option value=''>请选择</option>");
	}
	if(extraData.value != null){
		for(let entry of dataMap){
			if(extraData.pKeyName != null){
				let pKeyValue = extraData.pKeyValue;
				//循环遍历上级节点数组中元素
				for(let i = 0; i< pKeyValue.length; i++){
					if(entry[1][extraData.pKeyName] == pKeyValue[i]){
						if(entry[1][extraData.keyName] == extraData.value){
							str += "<option value='"+ entry[1][extraData.keyName] +"' selected='selected'>"+ entry[1][extraData.keyValue] +"</option>";
						}else{
							str += "<option value='"+ entry[1][extraData.keyName] +"'>"+ entry[1][extraData.keyValue] +"</option>";
						}
					}
				}
			}else{
				if(entry[1][extraData.keyName] == extraData.value){
					str += "<option value='"+ entry[1][extraData.keyName] +"' selected='selected'>"+ entry[1][extraData.keyValue] +"</option>";
				}else{
					str += "<option value='"+ entry[1][extraData.keyName] +"'>"+ entry[1][extraData.keyValue] +"</option>";
				}
			}
		}
	}else{
		for(let entry of dataMap){
			if(extraData.pKeyName != null){
				let pKeyValue = extraData.pKeyValue;
				//循环遍历上级节点数组中元素
				for(let i = 0; i< pKeyValue.length; i++){
					if(entry[1][extraData.pKeyName] == pKeyValue[i]){
						str += "<option value='"+ entry[1][extraData.keyName] +"'>"+ entry[1][extraData.keyValue] +"</option>";
					}
				}

			}else{
				str += "<option value='"+ entry[1][extraData.keyName] +"'>"+ entry[1][extraData.keyValue] +"</option>";
			}
		}
	}
	$("#" + extraData.id).append(str);
}


//初始化日期控件
function initDatePicker(arr){
	$.each(arr, function(index, value){
		$("#" + value).datepicker({
			dateFormat: "yy-mm-dd",
		});
	})
}

//初始化日期时间控件
function initDateTimeBox(arr){
	$.each(arr, function(index, value){
		$("#" + value).datetimebox({
			editable: false
		});
	})
}

//easyui日期格式化
function dateTimeFormatter(date) {
	let y = date.getFullYear();
	let m = date.getMonth() + 1;
	let d = date.getDate();
	let h = date.getHours();
	let min = date.getMinutes();
	let s = date.getSeconds();
	let str = y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + ' ' + (h < 10 ? ('0' + h) : h)
		+ ':' + (min < 10 ? ('0' + min) : min) + ':' + (s < 10 ? ('0' + s) : s);
	return str;
}

function dateTimeParser(s) {
	if (!s) return new Date();
	var y = s.substring(0, 4);
	var m = s.substring(5, 7);
	var d = s.substring(8, 10);
	var h = s.substring(11, 14);
	var min = s.substring(15, 17);
	var sec = s.substring(18, 20);
	if (!isNaN(y) && !isNaN(m) && !isNaN(d) && !isNaN(h) && !isNaN(min) && !isNaN(sec)) {
		return new Date(y, m - 1, d, h, min, sec);
	} else {
		return new Date();
	}
}

//获取url中请求的参数
function getQueryVariable(variable){
	let query = window.location.search.substring(1);
	let vars = query.split("&");
	for (let i = 0; i < vars.length; i++) {
		let pair = vars[i].split("=");
		if(pair[0] == variable){
			return pair[1];
		}
	}
	return false;
}